//
//  MZProgramDetailViewController.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 21/04/12.
//  Copyright 2012 Mehfile Zainab. All rights reserved.
//

#define FONT_SIZE 18.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 1.0f

#import "MZProgramDetailViewController.h"
#import "MZProgram.h"

@implementation MZProgramDetailViewController

@synthesize programItem;
@synthesize eventStore, defaultCalendar;

#pragma mark -
#pragma mark View lifecycle

-(void)addAgenda {
	
	NSLog(@"Add event to Calendar");
    
    // When add button is pushed, create an EKEventEditViewController to display the event.
	EKEventEditViewController *addController = [[EKEventEditViewController alloc] initWithNibName:nil bundle:nil];
	
	// set the addController's event store to the current event store.
	addController.eventStore = self.eventStore;
    
    EKEvent *thisEvent = addController.event;
    
    [thisEvent setTitle:programItem.getProgramTitle];
    
    NSString *addrName = @"Mehfile Zainab";
    NSString *addrValue = @"19, avenue Gabriel Péri";
    NSString *addrCity = @"93120 La Courneuve";
    NSString *addrLocation = [NSString stringWithFormat:@"%@\r%@\r%@", addrName,addrValue,addrCity];
    [thisEvent setLocation:addrLocation];

    NSURL *mzUrl = [[NSURL alloc] initWithString:@"http://www.mehfile-zainab.com"];
    [thisEvent setURL:mzUrl];
    
    NSString *startProgramDate = [NSString stringWithFormat:@"%@ %@", programItem.mzProgramDate, programItem.mzProgramStartTime];
    NSString *endProgramDate = [NSString stringWithFormat:@"%@ %@", programItem.mzProgramDate, programItem.mzProgramEndTime];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease]];
    [dateFormatter setDateFormat:@"eeee dd MMMM yyyy HH'h'mm"];
    NSDate *startDateFromString = [[NSDate alloc] init];
    startDateFromString = [dateFormatter dateFromString:startProgramDate];
    [thisEvent setStartDate:startDateFromString];
    NSDate *endDateFromString = [[NSDate alloc] init];
    endDateFromString = [dateFormatter dateFromString:endProgramDate];
    [thisEvent setEndDate:endDateFromString];

	// present EventsAddViewController as a modal view controller
	//[self presentModalViewController:addController animated:YES];
	[self presentViewController:addController animated:YES completion:nil];
    
	addController.editViewDelegate = self;
	[addController release];
	
}

- (void)viewDidLoad {
    [super viewDidLoad];
	
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(10,0,280,40)];
    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [aButton setTitle:@"Ajouter à mon calendrier" forState:UIControlStateNormal];
    [aButton setFrame:CGRectMake(10,0,280,40)];
    [aButton addTarget:self action:@selector(addAgenda) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:aButton];
    [self.tableView setTableFooterView:footerView];
	
    // Initialize an event store object with the init method. Initilize the array for events.
	self.eventStore = [[EKEventStore alloc] init];
    
    if([self.eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
        [self.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
            /* This code will run when uses has made his/her choice */
        }];
    }
    
	// Get the default calendar from store.
	self.defaultCalendar = [self.eventStore defaultCalendarForNewEvents];
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


// Overriding EKEventEditViewDelegate method to update event store according to user actions.
- (void)eventEditViewController:(EKEventEditViewController *)controller
          didCompleteWithAction:(EKEventEditViewAction)action {
	
	NSError *error = nil;
	EKEvent *thisEvent = controller.event;
	
	switch (action) {
		case EKEventEditViewActionCanceled:
			// Edit action canceled, do nothing.
			break;
			
		case EKEventEditViewActionSaved:
			// When user hit "Done" button, save the newly created event to the event store,
			// and reload table view.
			// If the new event is being added to the default calendar, then update its
			// eventsList.
			[controller.eventStore saveEvent:controller.event span:EKSpanThisEvent error:&error];
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Mehfile Zainab" message:@"Evènement ajouté à votre calendrier" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];
			break;
			
		case EKEventEditViewActionDeleted:
			// When deleting an event, remove the event from the event store,
			// and reload table view.
			// If deleting an event from the currenly default calendar, then update its
			// eventsList.
			[controller.eventStore removeEvent:thisEvent span:EKSpanThisEvent error:&error];
			break;
			
		default:
			break;
	}
	// Dismiss the modal view controller
	//[controller dismissModalViewControllerAnimated:YES];
	[controller dismissViewControllerAnimated:YES completion:nil];
    
}

// Set the calendar edited by EKEventEditViewController to our chosen calendar - the default calendar.
- (EKCalendar *)eventEditViewControllerDefaultCalendarForNewEvents:(EKEventEditViewController *)controller {
	EKCalendar *calendarForEdit = self.defaultCalendar;
	return calendarForEdit;
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    NSInteger sectionCount = 1;
	//NSString *programDesc = [[[programDict objectForKey:pList] objectAtIndex:pDetailIndex] objectForKey:pDesc];
	//if (programDesc) {
	NSString *programDescription = [programItem getProgramDescription];
	if ((programDescription!=nil) && ([programDescription length]!=0)) {
		sectionCount = 2;
	}
	return sectionCount;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger rowCount = 0;
	NSString *programDescription = [programItem getProgramDescription];
	//NSString *programDesc = [[[programDict objectForKey:pList] objectAtIndex:pDetailIndex] objectForKey:pDesc];
	switch (section) {
		case 0:
			rowCount = 1;
			break;
		case 1:
			if ((programDescription!=nil) && ([programDescription length]!=0)) {
				rowCount = 1;
			}
			break;
		default:
			break;
	}
	return rowCount;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	NSString *sectionTitle;
	switch (section) {
		case 0:
			//sectionTitle = [programDict objectForKey:pDate];
			sectionTitle = [programItem getProgramDate];
			break;
		case 1:
			sectionTitle = nil;
			break;
		default:
			sectionTitle = nil;
			break;
	}
	return sectionTitle;
	
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	CGFloat _height = 0.0;
	CGSize constraint;
	
	switch (indexPath.section) {
		case 0:
			_height = 45.0f;
			break;
		case 1:
			constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
			//CGSize size = [[[[programDict objectForKey:pList] objectAtIndex:pDetailIndex] objectForKey:pDesc] sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
			CGSize size = [[programItem getProgramDescription] sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
			_height = size.height + (CELL_CONTENT_MARGIN * 2);
			break;
		default:
			break;
	}
	return _height;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	/*
	NSString *program = [[[programDict objectForKey:pList] objectAtIndex:pDetailIndex] objectForKey:pTitle];
	NSString *programTime = [[[programDict objectForKey:pList] objectAtIndex:pDetailIndex] objectForKey:pStartDate];
	NSString *programDesc = [[[programDict objectForKey:pList] objectAtIndex:pDetailIndex] objectForKey:pDesc];
	*/
	
	NSString *programDescription = [programItem getProgramDescription];
	
    // Configure the cell...
	switch (indexPath.section) {
		case 0:
			//[cell.textLabel setText:program];
			[cell.textLabel setText:[programItem getProgramTitle]];
			//[cell.detailTextLabel setText:programTime];
			[cell.detailTextLabel setText:[programItem getProgramStartTime]];
			break;
		case 1:
			if ((programDescription!=nil) && ([programDescription length]!=0)) {
				cell.textLabel.font = [UIFont systemFontOfSize:16];
				cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
				cell.textLabel.numberOfLines = 0;
				//[cell.textLabel setText:programDesc];
				[cell.textLabel setText:[programItem getProgramDescription]];
			}
			break;
		default:
			break;
	}
	
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    // Navigation logic may go here. Create and push another view controller.
	/*
	 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 */
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end

